var record = [
    {name: '手机号10086', text: '一等奖'},
    {name: '手机号10010', text: '二等奖'},
    {name: '手机号10000', text: '三等奖'}
];
var jiang = [
    {name: "IPHONE X", weight: 1, probability: 1, color: "#ff0000"},

    {name: "IPHONE 8", weight: 1, probability: 2, color: "#00ff00"},

    {name: "IPHONE 7", weight: 1, probability: 2, color: "#0000ff"},

    {name: "小米手环", weight: 1, probability: 4, color: "#eeff00"},

    {name: "小米充电宝", weight: 1, probability: 4, color: "#0ff000"},

    {name: "优惠券10", weight: 1, probability: 8, color: "#ffff00"}
];
var localDate = window.localStorage.getItem('jiangxiang');
if (localDate) {
    jiang = JSON.parse(localDate)
}

/**
 * 绘制奖项图片
 * @param data
 * @returns {any[]}
 */
function drawPanel(data) {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.translate(180, 180);
    var R = 180;
    var sum = 0, sum2 = 0;
    data.forEach(function (value) {
        sum += value.weight
        sum2 += value.probability
    })
    var local = data.map(function (value) {
        return {
            name: value.name,
            color: value.color,
            angle: value.weight * 360 / sum,
            probability: value.probability / sum2
        };
    });

    sum = 0;
    local.forEach(function (value, index) {
        dc(value.angle, value.name, value.color || '#f00')
    });

    function dc(angle, name, color) {
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.arc(0, 0, R, Math.PI * (-90) / 180, Math.PI * (angle - 90) / 180, false)
        ctx.fillStyle = color;
        ctx.fill();
        ctx.closePath();
        ctx.rotate(Math.PI * angle / 360)

        ctx.fillStyle = '#000000';
        ctx.font = "18px Georgia";
        var width = ctx.measureText(name).width;
        var positionWidth = 2 * R * 0.7 * Math.tan(Math.PI * (angle / 2) / 180);

        if (width > positionWidth) {
            ctx.fillText("" + name, -width / 2, -R * 0.7);
            console.log('字太长了')
        } else {
            ctx.fillText("" + name, -width / 2, -R * 0.7);
        }

        ctx.rotate(Math.PI * angle / 360)
    }

    return local
}

/**
 * 绘制表盘
 * @type {any[]}：表盘度数对应的奖项
 */
var formatArray = drawPanel(jiang)

/**
 * 中奖纪录逻辑
 * @param doms
 * @param data
 * @constructor
 */
function Record(doms, data) {
    var current = doms.current;
    var next = doms.next;
    this.index = 0;
    setToHTML(current, data, this.index)
    setToHTML(next, data, this.index + 1)
    var _this = this;
    this.nextRecord = function () {
        var ff = 0;
        (_this.index < data.length - 1) ? _this.index++ : _this.index = 0;
        // 滚动动画
        var flag = setInterval(function () {
            current.style.marginTop = ff-- + 'px'
            if (ff === -24) {
                clearInterval(flag);
                var index = _this.index
                setToHTML(current, data, index)
                current.style.marginTop = '0px';
                var next_index = index >= data.length - 1 ? 0 : index + 1
                setToHTML(next, data, next_index)
            }
        }, 20)
    };

    function setToHTML(dom, data, index) {
        dom.innerHTML = '恭喜' + data[index].name + '获得' + '<span style="color: #feff26">' + data[index].text + '</span>'
    }
}

var rec = new Record({
    current: document.getElementById('current'),
    next: document.getElementById('next')
}, record);

/**
 * 定时更新中奖纪录
 */
setInterval(function () {
    rec.nextRecord();
}, 2000);

/**
 * 主要游戏逻辑
 * @param panel  转盘
 * @constructor
 */
function Game(panel) {
    var flag = null;
    this.flag = true;
    this.panel = panel;
    this.star = function () {
        zhaun(getRandByDate(formatArray), function (uu) {
            formatResult(uu, formatArray)
        })
    };
    this.stop = function () {
        zhaun(getRandByDate(formatArray), function (uu) {
            formatResult(uu, formatArray)
        })
    };

    function zhaun(angle, callback) {
        if (flag) return
        var t1 = 400, t2 = 500, speed = 10;
        console.log(angle);
        angle = angle - 20;
        var rot = 0, time = 0;
        var real_t1 = t1 + angle / speed;
        flag = setInterval(function (angle) {
            time++;
            if (time < real_t1) {
                rot = time * speed;
            } else {
                rot = real_t1 * speed + speed * (time - real_t1) - (speed / t2 / 2) * (time - real_t1) * (time - real_t1)
            }
            this.panel.style.transform = "rotate(" + rot + "deg)";
            if (time >= real_t1 + t2) {
                clearInterval(flag);
                flag = null
                var result = Math.ceil(rot - (speed * (t1 + t2) - 0.5 * speed * t2)) + 20;
                console.log('222', result)
                callback(result)
            }
        }, 1)
    }

    function ting() {
        clearInterval(flag);
    }
}

/**
 * 开始按钮的两种状态控制
 */
Game.prototype.toggle = function () {
    if (this.flag) {
        this.star()
    } else {
        this.stop()
    }
    this.flag = !this.flag
};

var Singleton = {};
/**
 * 获取游戏对象实例
 */
Singleton.getInstance = (function () {
    var instance = null;
    return function (name) {
        if (!instance) {
            instance = new Game(document.getElementById('panel'));
        }
        return instance;
    }
})();

/**
 * 按钮事件绑定
 */
document.getElementById('start').addEventListener('click', function () {
    var game = Singleton.getInstance(Game);
    game.toggle();
});

/**
 * 读圆盘的角度，转化为获奖的内容
 * @param num 圆盘转动的角度
 * @param formatArray 转盘角度对应的奖项
 */
function formatResult(num, formatArray) {
    for (var i = formatArray.length - 1; i >= 0; i--) {
        num = num - formatArray[i].angle;
        if (num <= 0) {
            showResult(formatArray[i].name);
            break;
        }
    }
}

/**
 * 展示抽奖结果
 * @param result
 */
function showResult(result) {
    alert(result)
}

/**
 * 根据每个奖项出现的概率，产生随机角度值
 */
function getRandByDate(data) {
    // 抽奖逻辑，产生随机数，根据概率范围确定获得奖品种类
    var rand = Math.random().toFixed(2);
    // prizeIndex：抽奖结果索引
    //[startAngle,ensAngle]为奖品对应角度
    var prizeIndex = 0, startAngle = 0, endAngle = 0
    for (var i = data.length - 1; i >= 0; i--) {
        rand -= data[i].probability;
        endAngle += data[i].angle
        if (rand < 0) {
            prizeIndex = i;
            break;
        }
    }
    //避免停留在边界
    startAngle = endAngle - data[prizeIndex].angle + 1
    endAngle--;
    // 在角度范围内产生随机数
    return Math.ceil(Math.random() * (endAngle - startAngle) + startAngle)
}


//-------------------数据设置有关--------------------
var table = document.getElementById('dataPanel');
var array = []

document.getElementById('add').addEventListener('click', function (ev) {
    var tr = document.createElement('tr');
    tr.innerHTML = '<td><input type="text"></td>\n' +
        '            <td><input type="number"></td>\n' +
        '            <td><input type="number"></td>' +
        '            <td><input type="text"></td>'
    table.childNodes[1].appendChild(tr)
});
document.getElementById('delete').addEventListener('click', function (ev) {
    table.childNodes[1].removeChild(table.childNodes[1].lastChild)
});
document.getElementById('ok').addEventListener('click', function (ev) {
    array = []
    Array.prototype.forEach.call(table.childNodes[1].childNodes, function (e) {
        if (e.nodeName.toLowerCase() === 'tr')
            array.push(e)
    })
    array = array.map(function (value, index) {
        if (index) {
            var cache = []
            Array.prototype.forEach.call(value.childNodes, function (e, index) {
                if (e.nodeName.toLowerCase() === 'td') {
                    console.log(e.firstChild.value)
                    cache.push(e.firstChild.value)
                }
            })
            return {
                name: (cache[0]),
                weight: Number(cache[1]),
                probability: Number(cache[2]),
                color: (cache[3])
            };
        }
    });
    array.shift();
    var flag = true
    array.forEach(function (value) {
        if (isNaN(value.weight)) {
            alert('请检查数据')
            flag = false
        }
        if (value.weight <= 0) {
            alert('图片所占要大于1')
            flag = false
        }
        if (isNaN(value.probability)) {
            alert('请检查数据')
            flag = false
        }
        if (value.probability < 0) {
            alert('不可以填写负数')
            flag = false
        }
    })
    /*  if (array.length === 1) {
          alert('数据不要少于一行')
          flag = false
      }*/
    if (flag) {
        window.localStorage.setItem('jiangxiang', JSON.stringify(array))
        window.location.reload()
        document.getElementById('cancel').click()
    }
});
document.getElementById('cancel').addEventListener('click', function (ev) {
    document.getElementById('setContainer').style.visibility = 'hidden'
})

;document.getElementById('setting').addEventListener('click', function (ev) {
    document.getElementById('setContainer').style.visibility = 'visible'
});

